package com.pirestupppai.ui.fragment;

import android.content.Context;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.LinearLayout;

import com.pirestupppai.R;
import com.pirestupppai.adapter.FeedListAdapter;
import com.pirestupppai.base.BaseFragment;
import com.pirestupppai.bean.FeedItem;
import com.pirestupppai.common.Constant;
import com.pirestupppai.network.NetworkRequest;
import com.pirestupppai.network.TupaiSubscriber;
import com.pirestupppai.rxbus.RxBus;
import com.pirestupppai.widgets.view.FeedRecommendLayout;
import com.pirestupppai.widgets.view.LoadMoreFooter;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import rx.Subscription;
import rx.functions.Action1;

import static com.pirestupppai.rxbus.RxBus.RXBUS_REFRESH_FEED_LIST;

/**
 * 关注动态页
 *
 * @author: xiaoluo
 * @date: 2017-03-03 17:07
 */
public class FeedFragment extends BaseFragment {
    private final static String TAG = FeedFragment.class.getSimpleName();

    @BindView(R.id.feed_recycler_view)
    RecyclerView recyclerView;
    @BindView(R.id.feed_swipe_layout)
    SwipeRefreshLayout swipeRefreshLayout;
    @BindView(R.id.status_bar)
    View statusBar;

    private FeedRecommendLayout mRecommendView;
    private LoadMoreFooter mFooterView;
    private FeedListAdapter mFeedListAdapter;
    private LinearLayoutManager mLinearLayoutManager;

    private long mLastRefreshTime = 0;
    private int mPosition = 0;  // 列表最后一位
    private int mPage = 1;
    private int mSize = 20;
    private boolean hasMore = true;
    private List<FeedItem> mFeedList = new ArrayList<>();

    private boolean isExpand = true;
    private boolean isScrollTop = false;
    private boolean isScrolling = false;

    private Subscription mSubscription;

    @Override
    protected Context getFragmentContext() {
        return getActivity();
    }

    @Override
    protected int loadParentLayout() {
        return R.layout.fragment_feed;
    }

    @Override
    protected void initViews() {
        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) statusBar.getLayoutParams();
        params.height = Constant.HEIGHT_OF_STATUSBAR;
        params.width = Constant.WIDTH_OF_SCREEN;
        statusBar.setLayoutParams(params);

        mRecommendView = new FeedRecommendLayout(mContext);
        mFooterView = new LoadMoreFooter(mContext);
//        swipeRefreshLayout.setColorSchemeColors(ContextCompat.getColor(mContext, R.color.colorAccent));
//        swipeRefreshLayout.setProgressViewOffset(true, 0,  (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 70, getResources().getDisplayMetrics()));

        mFeedListAdapter = new FeedListAdapter(mContext, mFeedList);
        mFeedListAdapter.setFooterView(mFooterView);
//        mFeedListAdapter.setRecommendView(mRecommendView);
        mLinearLayoutManager = new LinearLayoutManager(mContext);
        mLinearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);

        recyclerView.setLayoutManager(mLinearLayoutManager);
        recyclerView.setAdapter(mFeedListAdapter);
        recyclerView.setHasFixedSize(true);
//        recyclerView.addItemDecoration(new SpacesItemDecoration(10));

    }

    @Override
    protected void initListeners() {

        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                refresh();
            }
        });

        // 监听到达底部事件
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                //到达底部时,加载更多
                int lastVisiblePosition = mLinearLayoutManager.findLastCompletelyVisibleItemPosition() + 1;
                if (mLinearLayoutManager.getChildCount() > 0
                        && mLinearLayoutManager.getItemCount() >= mLinearLayoutManager.getChildCount()
                        && lastVisiblePosition >= mLinearLayoutManager.getItemCount()
                        && dy > 0) {
                    mPosition = lastVisiblePosition;

                    if (hasMore && !swipeRefreshLayout.isRefreshing()) {
                        mFooterView.setStatus(LoadMoreFooter.Status.LOADING);
                        loadMore();
                    }
                }

                // 防止滑到列表中间时，下拉引起下拉刷新
                int topRowVewrticalPosition =
                            (recyclerView == null || recyclerView.getChildCount() == 0) ? 0 : recyclerView.getChildAt(0).getTop();
                isScrollTop = (topRowVewrticalPosition >= 0);
                isCanRefresh();

            }

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
//                // 觉得滑动有点卡顿的话可以在滑动时取消图片加载,暂不需要
//                if (newState == RecyclerView.SCROLL_STATE_DRAGGING || newState == RecyclerView.SCROLL_STATE_SETTLING) {
//                    isScrolling = true;
//                    Glide.with(mContext).pauseRequests();
//                } else if (newState == RecyclerView.SCROLL_STATE_IDLE) {
//                    if (isScrolling == true) {
//                        Glide.with(mContext).resumeRequests();
//
//                    }
//                    isScrolling = false;
//                }
            }
        });
    }

    /**
     * 判断是否可以下拉刷新
     */
    private void isCanRefresh() {
        if (isExpand && isScrollTop) {
            swipeRefreshLayout.setEnabled(true);
        } else {
            if (!swipeRefreshLayout.isRefreshing()) {
                swipeRefreshLayout.setEnabled(false);
            }
        }
    }

    @Override
    protected void initLogic() {
        // 进入界面就刷新
        swipeRefreshLayout.post(new Runnable() {
            @Override
            public void run() {
                refresh();
                swipeRefreshLayout.setRefreshing(true);
            }
        });

        //注册观察者
        mSubscription = RxBus.getInstance()
                .toObservable(RXBUS_REFRESH_FEED_LIST, String.class)
                .subscribe(new Action1<String>() {
                    @Override
                    public void call(String s) {
                        refresh();
                    }
                });
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden) {
            swipeRefreshLayout.setRefreshing(false);
        }

        isCanRefresh();
    }

    /**
     * 下拉刷新
     */
    private void refresh() {
//        mRecommendView.setRecommendData();
        hasMore = true;
        mPage = 1;
        mLastRefreshTime = System.currentTimeMillis();
        mFooterView.setStatus(LoadMoreFooter.Status.GONE);
        NetworkRequest.getInstance().getFeedList(mPage, mSize,
                new TupaiSubscriber<List<FeedItem>>(mContext) {
                    @Override
                    protected void requestSuccess(List<FeedItem> feedItems) {
                        recyclerView.setVisibility(View.VISIBLE);
                        if (feedItems != null && feedItems.size() != 0) {
                            mFeedList.clear();
                            mFeedList.addAll(feedItems);
                            mFeedListAdapter.notifyDataSetChanged();
                        } else {
                            mFeedList.clear();
                            mFeedListAdapter.notifyDataSetChanged();
                        }
                        swipeRefreshLayout.setRefreshing(false);

                        if (feedItems != null && feedItems.size() < mSize) {
                            mFooterView.setStatus(LoadMoreFooter.Status.THE_END);
                            hasMore = false;
                        }

                        recyclerView.scrollToPosition(0);
                    }

                    @Override
                    protected void requestError(String error) {
                        swipeRefreshLayout.setRefreshing(false);
                    }
                });

    }

    /**
     * 上拉加载
     */
    private void loadMore() {
        mPage++;
        NetworkRequest.getInstance().getFeedList(mPage, mSize,
                new TupaiSubscriber<List<FeedItem>>(mContext) {
                    @Override
                    protected void requestSuccess(List<FeedItem> feedItems) {
                        if (feedItems != null && feedItems.size() != 0) {
                            mFeedList.addAll(feedItems);
                            mFeedListAdapter.notifyItemInserted(mPosition);
                            mFooterView.setStatus(LoadMoreFooter.Status.GONE);
                        } else {
                            mFooterView.setStatus(LoadMoreFooter.Status.THE_END);
                            hasMore = false;
                        }
                        swipeRefreshLayout.setRefreshing(false);
                        if (feedItems != null && feedItems.size() < mSize) {
                            mFooterView.setStatus(LoadMoreFooter.Status.THE_END);
                            hasMore = false;
                        }
                    }

                    @Override
                    protected void requestError(String error) {
                        mPage--;
                        mFooterView.setStatus(LoadMoreFooter.Status.GONE);
                        swipeRefreshLayout.setRefreshing(false);
                    }
                });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (!mSubscription.isUnsubscribed()) {
            mSubscription.unsubscribe();
        }
    }

}